<template>
  <Headers page="order" />
  <div class="content">
    <el-card>
      <template #header>回程信息</template>
      <el-date-picker
        v-model="form.usedate"
        type="date"
        placeholder="选择日期"
        size="large"
        value-format="YYYY-MM-DD"
        v-if="userStore.sceneDate == '1'"            
      />
      <el-divider />
      <el-descriptions       
        direction="vertical"
        :column="3"
        size="large"
        border       
      >
        <el-descriptions-item label="线路">{{ info.ferryname }}</el-descriptions-item>
        <el-descriptions-item label="车型">{{ info.suitname }}</el-descriptions-item>  
        <el-descriptions-item label="价格">{{ form.customPrice }}</el-descriptions-item>  
      </el-descriptions>
      <el-divider />
      <el-checkbox
        v-if="limit_driver_num>0"
        v-model="form.isdriver"
        label="司机跟车"
        size="large"
        border       
        @change="selectDriver"
      />
      <el-divider />
      <el-radio-group v-model="form.flightid">
        <el-radio
          v-for="item in flights"
          :key="item.id"
          :value="item.id"
          size="large"
          border
          class="mpb10"
          :disabled="item.stock <= 0 || (form.usedate == todayDate() && Number(item.displayorder)<Number(suitInfo.flightdisplayorder))"

        >
          <div>{{ item.title }}</div>
          <div>车：{{ Math.floor(item.stock/car_stock_ratio) }}</div>
          <div>司：{{ item.dstock }}</div>
        </el-radio>
      </el-radio-group>
      </el-card>
    <el-card class="mpt10 mpb10">
      <el-button
        type="primary"
        plain
        size="large"
        style="width: 100%"
        @click="submit"
        :disabled="btnDisabled"
        >提交订单</el-button
      >
    </el-card>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted,onUnmounted } from "vue";
import Headers from "@/components/Header.vue";
import request from "@/utils/request";
import { todayDate } from "@/utils/tools";
import { useUser } from "@/stores/user";

import { useRoute, useRouter } from "vue-router";
import { ElLoading } from "element-plus";
import { ElMessageBox } from "element-plus";

const route = useRoute();
const router = useRouter();


onMounted(() => {
  form.usedate = todayDate();  
  getBackData() 
  form.customPrice = Number(carprice.value) 
});

const btnDisabled = ref(false);
const userStore = useUser();
const flights=ref([])
const suitInfo=ref({})
const car_stock_ratio=ref()
const limit_driver_num = ref(0)
const driverprice = ref(0)
const carprice = ref(0)
const deduct_stock_type = ref('')
const stock_rule = ref([])
const info=reactive({
  suitname:'',
  ferryname:''
})
const form = reactive({
  ferryid: "",
  usedate: "",
  suitid: "",
  flightid: "",
  isdriver: "",
  carnum: "",
  cartype: "",
  size: "",
  driverName: "",
  driverIdcard: "",
  linkman: "",
  linktel: "",
  linkIdcard: "",
  paysource: "",
  customPrice:"",
  remark:"",
  weight:0,
  merchant_id:"",
  merchant_member_id:"",
  memberid:""
});

const selectDriver = (e)=>{
  if(e){
    form.customPrice = Number(carprice.value) +  Number(driverprice.value)
  }else{
    form.customPrice = Number(carprice.value)
  }
}

const get_detail = async () => { 
  let params = {
    url: "/scene/ferry/get_detail",
    method: "POST",
    data: {
      id: form.ferryid,
    },
  };
  let res = await request(params);
  if (res.status) {
    suitInfo.value = res.data   
  }
};


const book_suit = async () => {
  let params = {
    url: "/scene/ferry/book_suit",
    method: "POST",
    data: {
      ferry_id: form.ferryid,
      suit_id: form.suitid,
      date: form.usedate,
    },
  };
  let res = await request(params);
  if (res.status) {   
    driverprice.value = res.data.prices[0].driver_price;
    car_stock_ratio.value = res.data.prices[0].car_stock_ratio  
    limit_driver_num.value=res.data.prices[0].limit_driver_num   
    stock_rule.value=res.data.prices[0].stock_rule
    deduct_stock_type.value = res.data.prices[0].deduct_stock_type
    computeCarPrice()
  }
};

const computeCarPrice = ()=>{    
  let rex = new RegExp(/\d+/g)    
  let size = form.size.match(rex)[0]
  if(deduct_stock_type.value && stock_rule.value.length>0){   
    stock_rule.value.forEach(e => {
      if(e.stock>0 && e.max>0){        
        if(Number(size)>=Number(e.min) && Number(size)<=Number(e.max)){          
          car_stock_ratio.value = e.stock                
        }
      }
    });
  }
}

const getBackData = async (orderid) => {
  let params = {
    url: "/scene/order/get_back_info",
    method: "POST",
    data: {
      id:route.params.orderid
    },
  };
  let res = await request(params);
  if (res.status) {
    form.ferryid = res.data.ferryid
    form.usedate = res.data.usedate
    form.suitid = res.data.suitid
    form.carnum = res.data.carnum
    form.cartype= res.data.cartype
    form.size= res.data.size
    form.driverName= res.data.driverName
    form.driverIdcard= res.data.driverIdcard
    form.linkman= res.data.linkman
    form.linktel= res.data.linktel
    form.linkIdcard= res.data.linkIdcard
    form.paysource= res.data.paysource
    carprice.value= Number(res.data.price)
    form.customPrice =Number(res.data.price)
    form.remark= res.data.remark 
    form.merchant_id=res.data.merchant_id
    form.merchant_member_id=res.data.merchant_member_id
    form.memberid=res.data.memberid
    info.suitname= res.data.suitname
    info.ferryname = res.data.ferryname
    get_detail()
    book_suit()
    selectSuit() 
    computeCarPrice()
  }
};

const selectSuit = async (ferryid) => {
  let params = {
    url: "/scene/ferry/get_flight",
    method: "POST",
    data: {
      id: form.ferryid,
      usedate: form.usedate,
    },
  };
  let res = await request(params);
  if (res.status) {
    flights.value = res.data;    
  }
};

const submit = async () => {   
  let carist = [
    {
      carnumber: form.carnum,
      cartype: form.cartype,
      size: form.size,
    },
  ];
  let tourist;
  if (form.isdriver) {
    tourist = [
      {
        tourername: form.linkman,
        idcard: form.linkIdcard,
        cardtype: "身份证",
      },
    ];
  }
  let book_list = [
    {
      suit_id: form.suitid,
      sku_id: 0,
      num: 1,
      drivernum: form.isdriver ? 1 : 0,
      use_date: form.usedate,
      carist: carist,
      tourist: tourist ?? [],
      flight_id: form.flightid,
    },
  ];
  let params = {
    url: "/scene/ferry/add_order",
    method: "POST",
    data: {
      product_id: form.ferryid,
      linkman: form.linkman,
      linktel: form.linktel,
      linkidcard: form.linkIdcard,
      mobile: form.linktel,
      flight_id: form.flightid,
      source: 9,
      paysource: form.paysource,
      book_list: JSON.stringify(book_list),
      saleman: userStore.userName,
      salemanid: userStore.userId,
      customPrice:form.customPrice,
      remark:form.remark,
      merchant_id:form.merchant_id,
      merchant_member_id:form.merchant_member_id,
      mid:form.memberid
    },
  };
  const loadingInstance = ElLoading.service({
    fullscreen: true,
    text: "订单处理中...",
  });
  btnDisabled.value = true;
  let res = await request(params);
  if (res.status) {    
    router.push({
      name: "backview",
      params: { orderid: res.data.id },
    });
  } else {
    ElMessageBox.alert(res.msg, "错误");
  }
  btnDisabled.value = false;
  loadingInstance.close();
};
</script>

<style scoped>
.el-radio {
  height: 70px;
}
.content {
  margin: 20px auto;
  max-width: 600px;

  display: flex;
  flex-direction: column;
  justify-content: center;
}
.mpt10 {
  margin-top: 10px;
}
.mpb10 {
  margin-bottom: 10px;
}
.fr {
  float: right;
}
.price {
  font-size: 20px;
  color: red;
}
</style>